//
//  QuizParser.m
//  Quiz
//
//  Created by Anton Atanasov on 2/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "QuizParser.h"

@implementation QuizParser

- (id) initWithFileContents:(NSString*) xmlFile 
{
    QuizVO *quiz = [[QuizVO alloc] init];
    
    if (quiz) 
    {
        //initialization code
        
        CXMLDocument *doc	= [[[CXMLDocument alloc] initWithXMLString:xmlFile options:0 error:nil] autorelease];
        
        NSArray *nodes = NULL;
        CXMLElement *section = NULL;
        
        section = [doc rootElement];     
        
        subSections = [[NSMutableArray alloc] init];
        
        //	searching for books nodes
        nodes = [doc nodesForXPath:@"//quiz//question" error:nil];
        NSArray *arAttr=[section attributes];
        
        NSString *strValue;
        NSString *strName;
        
        NSUInteger i, countAttr = [arAttr count];
        for (i = 0; i < countAttr; i++) {
            strValue = [[arAttr objectAtIndex:i] stringValue];
            strName = [[arAttr objectAtIndex:i] name];
            if([QUIZ_ID compare:strName] == NSOrderedSame)
            {
                quiz.quizId = strValue;
            } 
            else if ([QUIZ_TITLE compare:strName] == NSOrderedSame)
            {
                quiz.title = strValue;
            }
        }
        
        //initialize the list of questions
        //TODO: add the initialization in the getter (lazy)
        quiz.questions = [[NSMutableArray alloc] init];
        
        QuestionVO *question;
        for (CXMLElement *node in nodes) 
        {
            question = [[QuestionVO alloc] init];
            //init answers array
            //TODO: add the initialiation in the getter (lazy)
            question.answers = [[NSMutableArray alloc] init];
            int counter;
            for(counter = 0; counter < [node childCount]; counter++) 
            {
                //	common procedure: dictionary with keys/values from XML node
                [subsection setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
                strValue = [[node childAtIndex:counter] stringValue];
                strName = [[node childAtIndex:counter] name];
                
                
                if([QUESTION_TEXT compare:strName] == NSOrderedSame)
                {
                    question.text = strValue;
                } 
                else if ([QUIZ_TITLE compare:strName] == NSOrderedSame)
                {
                    [question.answers addObject:strValue];
                }
                else if( [QUESTION_CORRECT_ANSWER compare:strName] == NSOrderedSame)
                {
                    question.correctAnswer = [strValue intValue];
                }
            }
            
            [quiz.questions addObject:question];
            
        }
    }
    
    return quiz;
}

@end
